const { v4: uuidv4 } = require("uuid");
const orderService = require("../service/order.service");
const dayjs = require("dayjs");

class OrderController {
  // 创建订单
  async create(ctx, next) {
    // 生成订单号
    const orderNumber = uuidv4();
    const userId = ctx.user.id;
    let { totalPrice, startDate, endDate, totalRestNight, listId } =
      ctx.request.body;
    startDate = dayjs(startDate).format("YYYY-MM-DD HH:mm:ss");
    endDate = dayjs(endDate).format("YYYY-MM-DD HH:mm:ss");
    const res = await orderService.insertUserOrder(
      orderNumber,
      userId,
      listId,
      totalPrice,
      startDate,
      endDate,
      totalRestNight
    );
    ctx.body = {
      status: 201,
      message: "创建订单成功",
      order: {
        orderNumber,
        startDate,
        endDate,
        totalPrice,
        totalRestNight,
        listId,
      },
    };
  }
  // 支付完成修改订单状态
  async paid(ctx, next) {
    const { orderNumber } = ctx.request.body;
    await orderService.updateStatusToPaid(orderNumber);
    ctx.body = {
      status: 201,
      message: "支付成功",
    };
  }
  // 获取所有行程订单
  async getAllTrip(ctx, next) {
    const userId = ctx.user.id;
    // 当前时间
    const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
    const nowDate = new Date(now);
    const res = await orderService.getOrdersByUserId(userId);
    try {
      res.forEach(async (item) => {
        const startDate = new Date(item.startDate);
        const endDate = new Date(item.endDate);
        // 行程进行中
        if (nowDate >= startDate && now < endDate) {
          await orderService.updateStatusByTime("ing", item.id);
          item.status = "ing";
        }
        // 行程已结束
        if (nowDate >= endDate) {
          await orderService.updateStatusByTime("completed", item.id);
          item.status = "completed";
        }
      });
    } catch (err) {
      console.log(err);
    }
    ctx.body = {
      status: 200,
      data: {
        res,
      },
    };
  }
  // 取消行程
  async cancelTrip(ctx, next) {
    const { orderNumber } = ctx.request.body;
    await orderService.deleteOrderByNumber(orderNumber);
    ctx.body = {
      status: 200,
      message: "成功取消行程",
    };
  }
}

module.exports = new OrderController();
